<!-- cloak设置  -->
<template>
  <ContentWrap :show-border="false">
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px search-form"
      label-width="68px"
      label-position="left"
    >
      <el-form-item label="规则名称" prop="name">
        <el-input
          v-model="queryParams.name"
          class="!w-240px"
          clearable
          placeholder="请输入"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备" prop="supportedDevices">
        <el-select
          v-model="queryParams.supportedDevices"
          class="!w-240px"
          clearable
          placeholder="请选择"
          @change="getList"
        >
          <el-option
            v-for="item in supportedDevicesType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item class="p-0 m-0" style="border: none !important">
        <el-button @click="handleQuery" type="primary" color="#3366ff"> 搜索 </el-button>
        <el-button class="border-none" @click="resetQuery">
          <Icon class="mr-5px" icon="ant-design:clear-outlined" />
          清除条件
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap :show-border="false">
    <el-row :gutter="10" class="mt-4 mb-4">
      <el-col :span="1.5" class="el-btn">
        <el-button type="primary" color="#3366ff" class="add-website-btn" @click="handleCloak">
          <Icon class="mr-2px" icon="ep:plus" />
          新增规则
        </el-button>
      </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="list"
      :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#333' }"
      class="rounded-lg"
    >
      <el-table-column label="规则名称" min-width="90" prop="name" />
      <el-table-column
        label="地区"
        min-width="90"
        prop="area"
        :filters="regionFiltersAdress"
        :filter-method="filterHandler"
      >
        <template #filter-icon>
          <Icon class="ml-2px" icon="ic:baseline-filter-alt" />
        </template>
        <!-- 自定义筛选弹窗内容 -->
        <template #filter="{ column }">
          <div class="custom-filter-panel">
            <!-- 搜索框 -->
            <el-input
              v-model="searchText"
              placeholder="搜索地区"
              clearable
              size="small"
              style="margin-bottom: 10px"
            />

            <!-- 筛选选项列表 -->
            <div style="max-height: 200px; overflow-y: auto">
              <el-checkbox-group v-model="selectedRegions">
                <el-checkbox
                  v-for="item in filteredOptions(column.filters)"
                  :key="item.value"
                  :label="item.value"
                  style="display: block; margin: 5px 0"
                >
                  {{ item.text }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="设备" prop="supportedDevices" width="180" />
      <el-table-column :formatter="dateFormatter" label="是否启用" prop="stock" width="180">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            active-color="#3721FF"
            inactive-color="#3721FF"
            :active-value="0"
            :inactive-value="1"
            @change="handleSwitch(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建者" prop="nickName" width="180" />
      <el-table-column :formatter="dateFormatter" label="创建时间" prop="createTime" width="180" />
      <el-table-column align="center" fixed="right" label="操作" class-name="all-button">
        <template #default="{ row }">
          <el-button link type="primary" color="#3721FF" plain @click="handleEdit(row.id)">
            编辑
          </el-button>
          <el-button link type="primary" color="#3721FF" plain @click="handleDelete(row.id)">
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 正常删除弹窗 -->
  <ComfirmPops
    ref="deletePopsRef"
    :show-icon="false"
    width="500px"
    :show-dot="true"
    type="idTips"
    title="删除"
    :id="delSelected"
    @confirm="getDeletePops"
  >
    <template #content>
      <p class="text-center">确定删除吗？</p>
    </template>
  </ComfirmPops>
  <!-- IP拉黑弹窗 -->
  <!-- <ComfirmPops
    ref="addCloakRef"
    :show-icon="false"
    width="700px"
    :show-dot="true"
    type="radio"
    title="新增"
    @confirm="getCloak"
  >
    <template #content>
      <el-form
        :model="formData"
        :rules="rules"
        ref="formDataRef"
        label-width="80px"
        label-position="left"
        class="w-[100%] pl-10px pr-20px"
      >
        <el-row>
          <el-col :span="15">
            <el-form-item label="类型" prop="type">
              <el-select v-model="formData.type" placeholder="请选择">
                <el-option label="IP" value="ip" />
                <el-option label="域名" value="domain" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="内容" prop="ip">
          <el-input v-model="formData.reason" type="textarea" :rows="7" placeholder="请输入..." />
        </el-form-item>
        <el-form-item label="备注" prop="reason">
          <el-input v-model="formData.reason" type="textarea" :rows="7" placeholder="请输入..." />
        </el-form-item>
      </el-form>
    </template>
  </ComfirmPops> -->
  <AddCloak ref="addCloakRef" :show-dot="true" @confirm="getCloak" :title="selectId ? '编辑' : '新增'" width="700px" />
</template>
<script lang="ts" setup>
import { TabsPaneContext } from 'element-plus'
import { createImageViewer } from '@/components/ImageViewer'
import { dateFormatter } from '@/utils/formatTime'
import ComfirmPops from '@/components/ComfirmPops/index.vue'
import AddCloak from './addCloak.vue'
import { defaultProps, handleTree, treeToString } from '@/utils/tree'
import { fenToYuan } from '@/utils'
import download from '@/utils/download'
import * as ProductSpuApi from '@/api/mall/product/spu'
import * as ProductCategoryApi from '@/api/mall/product/category'
import { WebCloakApi } from '@/api/website/cloak'
import { handlegetLanguageList, handleGetGlobeState } from '@/utils/index'
// supported_devices_type
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict' //获取字典
const supportedDevicesType = ref(getStrDictOptions(DICT_TYPE.SUPPORTED_DEVICES_TYPE))
defineOptions({ name: 'Cloak' })
const formDataRef = ref() // 表单的Ref
const deletePopsRef = ref() // 删除弹窗的Ref
const message = useMessage() // 消息弹窗
const route = useRoute() // 路由
// const { push } = useRouter() // 路由跳转
const addCloakRef = ref() // IP拉黑弹窗的Ref
const loading = ref(false) // 列表的加载中
const exportLoading = ref(false) // 导出的加载中
const total = ref(0) // 列表的总页数
// const isAddCopy = ref(false) // 是否复制
// const copyId = ref(0) // 复制的ID
const list = ref<ProductSpuApi.Spu[]>([]) // 列表的数据
const delSelected = ref(0) // 删除的ID
const selectId = ref(null)
const isAddIp = ref(false) // 是否新增网站组件
const isCloak = ref(false) // 是否显示批量导入
// 所有可筛选的地区选项
const regionFiltersAdress = ref([])
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  name: '',
  supportedDevices: ''
}) // 查询参数
const queryFormRef = ref() // 搜索的表单Ref
const formData = ref({
  // type: 'ip', // 类型
  // ip: '',
  // reason: ''
}) // IP拉黑表单数据
const rules = ref({
  // ip: [{ required: true, message: '请输入拉黑IP', trigger: 'blur' }],
  // reason: [{ required: true, message: '请输入拉黑原因', trigger: 'blur' }]
}) // IP拉黑表单验证规则
// 搜索关键词
const searchText = ref('')
// 已选中的地区
const selectedRegions = ref([])
const router = useRouter() // 路由

// const goSetNavigation = () => {
//   router.push({ name: 'SetNavigation' })
// }
// 修改状态
const handleSwitch = async (row) => {
  await WebCloakApi.updateWebCloakStatus({id:row.id, status:row.status})
  message.success('修改成功')
  getList()
}
const getCloak = (form) => {
  //   if (formData.value.ip == '') {
  //     message.error('请输入拉黑IP')
  //     return
  //   }
  //   if (formData.value.reason == '') {
  //     message.error('请输入拉黑原因')
  //     return
  //   }
  submitForm(form)
  addCloakRef.value.hide()
}
const handleCloak = () => {
  selectId.value = null
  addCloakRef.value.show()
}
const submitForm = async (form) => {
  loading.value = true
  try {
    if (form.id) {
      await WebCloakApi.updateWebCloak(form)
      message.success('修改规则成功')
      getList() // 刷新列表
      addCloakRef.value?.resetForm()
      loading.value = false
    } else {
      await WebCloakApi.createWebCloak(form)
      message.success('新增规则成功')
      getList() // 刷新列表
      addCloakRef.value?.resetForm()
      loading.value = false
      // formData.value.ip = ''
      // formData.value.reason = ''
    }
  } catch (error) {
    message.error('新增规则失败')
    loading.value = false
  }
}
// 根据搜索词过滤选项
const filteredOptions = (filters) => {
  return filters.filter((item) => item.text.includes(searchText.value))
}
// 筛选逻辑
const filterHandler = (value: string, row: any, column: TableColumnCtx<any>) => {
  const property = column['property']
  return row[property] === value
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await WebCloakApi.getWebCloakPage(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 切换 Tab */
const handleTabClick = (tab: TabsPaneContext) => {
  queryParams.value.tabType = tab.paneName as number
  getList()
}
const handleEdit = (id: number) => {
  selectId.value = id
  addCloakRef.value.show(id)
}
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  delSelected.value = id
  deletePopsRef.value.show()
}
const getDeletePops = async (res: boolean, id: number) => {
  console.log('isConfirm', res, id)
  if (res) {
    await WebCloakApi.deleteWebCloak(id).then((res) => {
      message.success('删除成功')
      getList()
    })
    // deletePopsRef.value.hide()
  } else {
    // deletePopsRef.value.hide()
  }
}

/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 新增或修改 */
// const openForm = (id?: number) => {
//   // 修改
//   if (typeof id === 'number') {
//     push({ name: 'ProductSpuEdit', params: { id } })
//     return
//   }
//   // 新增
//   push({ name: 'ProductSpuAdd' })
// }

// /** 查看商品详情 */
// const openDetail = (id: number) => {
//   push({ name: 'ProductSpuDetail', params: { id } })
// }

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ProductSpuApi.exportSpu(queryParams.value)
    download.excel(data, '商品列表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取分类的节点的完整结构 */
const categoryList = ref() // 分类树
const formatCategoryName = (categoryId: number) => {
  return treeToString(categoryList.value, categoryId)
}

/** 激活时 */
onActivated(() => {
  getList()
})

/** 初始化 **/
onMounted(async () => {
  // 解析路由的 categoryId
  if (route.query.categoryId) {
    queryParams.value.categoryId = route.query.categoryId
  }
  // 获得商品信息
  //   await getTabsCount()
  let adress = await handleGetGlobeState()
  regionFiltersAdress.value = adress.map((item) => {
    return {
      ...item,
      text: item.label,
      value: item.label
    }
  })
  await getList()
  // 获得分类树
  const data = await ProductCategoryApi.getCategoryList({})
  categoryList.value = handleTree(data, 'id', 'parentId')
})
</script>
<style scoped>
@import '@/styles/website.scss';
</style>
